package com.lx.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.lx.bean.User;
import com.lx.feign.UserFeign;
import com.lx.vo.MyMap;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("user")
@RefreshScope
public class UserController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UserFeign userFeign;


    //Hystrix断路器断路返回方法
    public Object queryUserByPageFallback(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                          @RequestParam(value = "limit", defaultValue = "5") Integer limit,
                                          @RequestParam(value = "column",defaultValue = "",required = false) String column,
                                          @RequestParam(value = "value",defaultValue = "",required = false) String value){
        MyMap myMap = new MyMap();
        myMap.put("page",page);
        myMap.put("limit",limit);
        myMap.put("column",column);
        myMap.put("value",value);
        myMap.put("message","queryUserByPageFallback方法，请确认用户服务是否启动");
        return myMap;
    }
    @HystrixCommand(fallbackMethod = "queryUserByPageFallback")
    @RequestMapping("queryUserByPage")
    public Object queryUserByPage(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                  @RequestParam(value = "limit", defaultValue = "5") Integer limit,
                                  @RequestParam(value = "column",defaultValue = "",required = false) String column,
                                  @RequestParam(value = "value",defaultValue = "",required = false) String value){
        /*
        String url = "http://usermodule/user/queryUserByPage?" +
                "pageIndex="+page+
                "&rows="+limit+
                "&column="+column+
                "&value="+value;
        Object object = restTemplate.getForObject(url, Object.class);
        */
        List<User> users = userFeign.queryUserByPage(page, limit, column, value);

        /*
        String url2 = "http://usermodule/user/queryUserCount?"+
                "&column="+column+
                "&value="+value;
        Integer total = restTemplate.getForObject(url2, int.class);
        */
        Integer total = userFeign.queryUserCount(column, value);

        return new MyMap().put("data",users).put("count", total);
    }

    @HystrixCommand
    @RequestMapping("deleteById")
    public Object deleteUserById(Integer id) throws IOException {
//        String url = "http://usermodule/user/deleteUserById/"+id;
//        restTemplate.delete(url);
        Map map = userFeign.deleteUserById(id);
        MyMap myMap = new MyMap();
        myMap.putAll(map);//将服务层的方法封装进MyMap对象中返回给前端
        return myMap;
    }

    /**
     * 使用String字符串，json格式 -> [2,3,4]
     * 在用户模块将 [2,3,4] 转换成List<Integer> 传往后台用户模块
     * @param ids
     * @return
     *
     * 或者使用Integer[]数组，使用字符串拼接的形式，循环将ids拼接到url后方，
     * 传递Integer数组到用户模块
     */
    @HystrixCommand
    @DeleteMapping("/deleteByIds")
    public Map deleteAnyStudent(@RequestBody Integer[] ids){
        /*//方式1
        String url = "http://usermodule/user/deleteUserByIds/{1}";
        restTemplate.delete(url,ids);
        */
        /*
        //方式2 使用Integer数组方式
        String params = "";
        for(Integer id:ids){
            params+= "ids="+id+"&";
        }
        String url1 = "http://usermodule/user/deleteUserByIds?"+params;
        System.out.println("url1 = " + url1);
        restTemplate.delete(url1);
        */
        Map map = userFeign.deleteUserByIds(ids);
        MyMap myMap = new MyMap();
        myMap.putAll(map);//将服务层的方法封装进MyMap对象中返回给前端
        return myMap;
    }

    @HystrixCommand
    @RequestMapping("login")
    public Object userLogin(@RequestBody User user){
        System.out.println("user = " + user);
        Map map = userFeign.userLogin(user);
        System.out.println("UserController.loginTest");
        MyMap myMap = new MyMap();
        myMap.putAll(map);//将服务层的方法封装进MyMap对象中返回给前端
        return myMap;
    }

    @HystrixCommand
    @RequestMapping("genderCount")
    public Object genderCount(){
        /*
        String url = "http://usermodule/user/genderCount";
        Object object = restTemplate.getForObject(url, Object.class);
        */
        List<Map> maps = userFeign.genderCount();
        return maps;
    }
    @HystrixCommand
    @RequestMapping("uploadPhoto")
    public Object uploadPhoto(MultipartFile photo,HttpServletRequest req){
        String realPath = req.getRealPath("/images/");
        String originalFilename = photo.getOriginalFilename();
        MyMap map = new MyMap();
        try(
                InputStream in = photo.getInputStream();//获取文件的输入流
                OutputStream out = new FileOutputStream(realPath + originalFilename);//输出文件到目标文件夹
        ){
            FileCopyUtils.copy(in,out);
            map.put("path", originalFilename);
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }
    @HystrixCommand
    @RequestMapping("addUser")
    public Object addUser(@RequestBody User user) throws JsonProcessingException {
        /*
        //不使用 feign发送对象的方式
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(user);//将user对象转换为json字符串

        HttpHeaders headers = new HttpHeaders();//设置请求头为 json 数据
        headers.setContentType(MediaType.APPLICATION_JSON);
        //将请求头和json数据封装到 request 中
        HttpEntity<String> request = new HttpEntity<String>(s, headers);

        String url = "http://usermodule/user/registerUser";
        Object body = restTemplate.postForEntity(url,request, Object.class).getBody();
        */
        Map map = userFeign.registerUser(user);
        MyMap myMap = new MyMap();
        myMap.putAll(map);//将服务层的方法封装进MyMap对象中返回给前端
        return myMap;
    }

    @HystrixCommand
    @RequestMapping("updateUser")
    public Object updateUser(@RequestBody User user) throws JsonProcessingException {
        /*
        //不使用 feign发送对象的方式
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(user);//将user对象转换为json字符串

        HttpHeaders headers = new HttpHeaders();//设置请求头为 json 数据
        headers.setContentType(MediaType.APPLICATION_JSON);
        //将请求头和json数据封装到 request 中
        HttpEntity<String> request = new HttpEntity<String>(s, headers);

        String url = "http://usermodule/user/updateUser";
        restTemplate.put(url,request, Object.class);
         */
        Map map = userFeign.updateUser(user);
        MyMap myMap = new MyMap();
        myMap.putAll(map);//将服务层的方法封装进MyMap对象中返回给前端
        return myMap;
    }


}
